package com.example.asus.happy;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.happy.service.address.Address;
import com.example.asus.happy.service.application.MyApplication;
import com.example.asus.happy.service.finaldata.FinalData;
import com.example.asus.happy.service.model.Comment;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class jokeListDetailActivity extends AppCompatActivity implements View.OnClickListener{

    private SwipeRefreshLayout mSwipeLayout;
    private TextView contentTV,backTV;
    private Button laudBtn,discussBtn,sendBtn,button4;
    private EditText discussET;
    private String url,url1,userName;
    private int c_id;
    private ListView discussList;
    private MyAdapter myAdapter;
    private List<Comment> list;
    private String content;

    public void init(){
        contentTV = (TextView) findViewById(R.id.contentTV);
        laudBtn = (Button) findViewById(R.id.laudBtn);
        discussBtn = (Button) findViewById(R.id.discussBtn);
        backTV = (TextView) findViewById(R.id.backTV);
        sendBtn = (Button)findViewById(R.id.sendBtn);
        discussET = (EditText)findViewById(R.id.discussET);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        discussList = (ListView)findViewById(R.id.discussList);
        button4 = (Button)findViewById(R.id.button4);//分享按钮，分享功能

        //接收笑话内容传过来的值
        Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();

        userName = getApp().getUserName();
        c_id = bundle.getInt("c_id");//内容id
        String content = bundle.getString("content");//笑话内容
        int laud = bundle.getInt("laud");//点赞数量
        int discuss = bundle.getInt("discuss");//评论数量

        url = Address.ADDRESS+"comment_json_Other?c_id="+c_id;//查询对应内容的评论
        contentTV.setText(content);
        laudBtn.setText(FinalData.LAUD+FinalData.LEFT+laud+FinalData.RIGHT);
        discussBtn.setText(FinalData.DISCUSS+FinalData.LEFT+discuss+FinalData.RIGHT);
    }


    //处理下拉刷新的Handler
    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 1:
                    mSwipeLayout.setRefreshing(false);
                    Toast.makeText(jokeListDetailActivity.this, FinalData.DISCUSS_REFRESH, Toast.LENGTH_SHORT).show();
                    break;
            }
        };
    };

    //处理显示评论内容Handler
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String response = (String)msg.obj;
                    list = getCarte(response);
                    myAdapter = new MyAdapter();
                    discussList.setAdapter(myAdapter);
                    mHandler.sendEmptyMessage(1);
                    break;
                default:
                    break;
            }
        }

    };

    //处理添加评论内容Handler
    private Handler handler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String response = (String)msg.obj;
                    if ("1".equals(response)){
                        Toast.makeText(jokeListDetailActivity.this, FinalData.DISCUSS_ADD_SUCC, Toast.LENGTH_SHORT).show();
                        //清空评论框
                        discussET.setText("");
                        //刷新显示
                        HttpPostRequest();
                    }
                    break;
                default:
                    Toast.makeText(jokeListDetailActivity.this, FinalData.NONETWORK, Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };


    //处理显示评论内容HttpPostRequest
    private void HttpPostRequest(){
        //处理显示内容的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,"UTF-8"));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,"UTF-8");
                        Message message = new Message();
                        message.what = 0;
                        message.obj = count.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }


    //处理添加评论HttpPostRequest
    private void HttpPostRequest1(final String url1){
        //处理显示内容的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url1);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,"UTF-8"));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,"UTF-8");
                        Message message = new Message();
                        message.what = 0;
                        message.obj = count.toString();
                        handler1.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //将接受到的json数据转换成对象，加入集合
    private List<Comment> getCarte(String product){
        try{
            JSONArray jarray = new JSONArray(product);
            List<Comment> commentList = new ArrayList<Comment>();
            for (int i=0;i<jarray.length();i++){
                JSONObject obj = new JSONObject(jarray.get(i).toString());
                Comment comment = new Comment();
                comment.setU_userName(obj.getString("u_userName")+":");
                comment.setM_ct(obj.getString("m_ct"));
                commentList.add(comment);
            }
            return commentList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_joke_list_detail);

        //初始化控件
        init();
        //返回TV点击事件
        backTV.setOnClickListener(this);
        //发送按钮
        sendBtn.setOnClickListener(this);
        //分享
        button4.setOnClickListener(this);
        //显示所有该内容的评论
        HttpPostRequest();

        //下拉刷新
        mSwipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //执行刷新方法
                HttpPostRequest();
            }
        });

    }

    //按钮点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.backTV :
                finish();
                break;
            case R.id.sendBtn :
                //发送按钮
                //获取评论内容
                String discuss = discussET.getText().toString();
                if ("".equals(discuss)){
                    Toast.makeText(this, FinalData.NODISCUSS, Toast.LENGTH_SHORT).show();
                }else {
                    url1 = Address.ADDRESS+"addComment?m_ct="+discuss+"&c_id="+c_id+"&u_userName="+userName;
                    HttpPostRequest1(url1);
                }
                break;
            case R.id.button4:
                // 分享文字，调用系统接口,首页的分享
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_TEXT, content);
                shareIntent.setType("text/plain");
                //设置分享列表的标题，并且每次都显示分享列表
                startActivity(Intent.createChooser(shareIntent, "分享到"));
                break;
        }
    }



    //获取application
    public MyApplication getApp(){
        return (MyApplication) getApplicationContext();
    }

    //自定义适配器
    public class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, final View convertView, ViewGroup parent) {
            final View view = getLayoutInflater().inflate(R.layout.discusslist_item,null);

            final Comment c = list.get(position);
            ((TextView)view.findViewById(R.id.userNameTV)).setText(c.getU_userName());
            ((TextView)view.findViewById(R.id.discussTV)).setText(c.getM_ct());

            return view;
        }
    }
}
